<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>对象类型</title>
    <script>
        function f1(){
            // 可以表示任意对象
            let obj = new Object();
            // 该对象可以有任意属性
            // 赋值
            obj.id = 1;
            // 取值
            console.log("id属性:"+obj.id)
            obj.name = "admin"
            console.log("name属性:"+obj.name)
            obj.a = "test"
            console.log("a属性:"+obj.a)
        }

        function f2(){
            let user = new User(1,"admin","123456");
            console.log(user)
        }

        function User(id,username,password){
            this.id = id;
            this.username = username;
            this.password = password;
        }
        function f3(){
            // 使用JSON语法定义对象
            let user = {'id':1,'username':'admin','password':'111111'};
            console.log(user);
            console.log(typeof user);
        }
        function f4(){
            // 定义一个JSON格式的字符串
            let s = "{'id':1,'username':'admin','password':'111111'}";
            console.log(typeof s)
            // 方式一:通过eval()方法将该字符串转换成JSON格式
            // 此时要求:
            // 1.该字符串具体内容必须符合JSON语法
            // 2.转换时参数值需要通过小括号将字符串括起来
            let user = eval("("+s+")");
            console.log(typeof user)
            console.log(user)
            console.log("***********************************")

            let s2 = '{"id":1,"username":"admin","password":"123456"}';
            console.log(typeof s2);
            let user2 = eval("("+s2+")");
            console.log(typeof user2)
            console.log(user2)
            console.log("***********************************")

            // 方式二:通过JSON.parse()进行转换
            // 该方法存在限制,转换的字符串必须是单引号的
            user2 = JSON.parse(s2);
            console.log(typeof user2)
            console.log(user2)
            console.log("***********************************")
            user = JSON.parse(s);
            console.log(typeof user)
            console.log(user)
        }
    </script>
</head>
<body>
<button onclick="f1()">定义方式一</button><br>
<button onclick="f2()">定义方式二</button><br>
<button onclick="f3()">定义方式三</button><br>
<button onclick="f4()">定义方式四</button><br>
</body>
</html>